<template>
  <div class="container">
    <div class="main-content">
      <!-- 左侧图像显示区域 -->
      <div class="image-container">
        <div class="grid-container">
          <div class="grid-item">
            <canvas ref="originalCanvas" width="100%" height="100%"></canvas>
          </div>
          <div ref="canvasContent">
          </div>
        </div>
        <div v-if="contourCount !== null" class="count-display">
          检测到的目标数量: {{ contourCount }}
        </div>
      </div>
      
      <!-- 右侧控制面板 -->
      <div class="control-panel">
        <div class="tab-header">
          <button class="tab-btn active">直方图</button>
          <button class="tab-btn">测试结果</button>

          
        </div>
        
        <div class="panel-section">
          <h3>读图</h3>
          <div class="button-group">
            <button @click="selectImage">选择图片</button>
            <button @click="selectImages">批量导入</button>
            <button>恢复原图</button>

          </div>
        </div>

        <div class="panel-section">
          <h3 class="child">分割阈值</h3>
          <div class="threshold-control child">
            <span>阈值：</span>
            <div class="threshold-input-group">
              <button 
                class="adjust-btn" 
                @click="down"
              >-</button>
              <input 
                type="range" 
                v-model="threshold" 
                min="0" 
                max="255" 
                step="1"
                @input="calculate"
              >
              <button 
                class="adjust-btn" 
                @click="up"
              >+</button>
              <input 
                type="number" 
                v-model="threshold" 
                min="0" 
                max="255" 
                step="1"
                class="number-input"
                @input="limitThreshold"
              >
            </div>
          

          </div>
          <div class="child">
              <button class="bt" @click="sendImage">计算</button>
              <button class="bt" @click="calculate">自动计算</button>
            </div>
            
        </div>
        <div class="panel-section">
          <h3>灰度计算（>阈值为荧光）</h3>
          <div class="results">
            <div class="result-item">
              <span>背景强度：</span>
              <input type="text" :value="bgIntensity" readonly>
              <button>直方图</button>
            </div>
            <div class="result-item">
              <span>荧光强度：</span>
              <input type="text" :value="fluorescence" readonly>
              <button>直方图</button>
            </div>
          </div>
        </div>

        <div class="panel-section">
          <h3>单通道荧光计算（>阈值）</h3>
          <div class="channel-results">
            <div class="result-item">
              <span>R强度：</span>
              <input type="text" :value="rIntensity" readonly>
              <button>直方图</button>
            </div>
            <div class="result-item">
              <span>G强度：</span>
              <input type="text" :value="gIntensity" readonly>
              <button>直方图</button>
            </div>
            <div class="result-item">
              <span>B强度：</span>
              <input type="text" :value="bIntensity" readonly>
              <button>直方图</button>
            </div>
          </div>
        </div>

        <div class="panel-section">
          <div class="table-header">
            <h3>结果列表</h3>
            <button @click="exportEvent">导出 CSV 文件</button>
          </div>
          <div class="table-section">
            <Table ref="tableRef" :tableData="resultsList"/>
          </div>
        </div>
       
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import Table from './Table.vue'
import ImageWorker from '@/utils/WorkTools.js?worker'; // 添加?worker后缀[1,6](@ref)
const worker = new ImageWorker();
let originalMat = null;
const originalCanvas=ref(null)
//导出csv分析表
const exportEvent = () => {
  console.log('导出CSV文件')
  tableRef.value.exportData(fileName.value)
}
// 上调阈值
const down = () => {
  threshold.value = Math.max(0, threshold.value - 1);
  console.log(threshold.value);
  calculate();
}
//下调阈值
const up = () => {
  threshold.value = Math.min(255, Number(threshold.value) + 1);
  console.log(threshold.value);
  calculate();
}
//阈值限制不超出0-255
const limitThreshold=()=> {
      if (threshold.value < 0) {
        threshold.value = 0;
      } else if (threshold.value > 255) {
        threshold.value = 255;
      }
}


//打开本地图片
const selectImage = async() => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.onload = () => {
          // 等待DOM更新完成后再获取尺寸
          setTimeout(() => {            
              const width = img.naturalWidth
              const height = img.naturalHeight
              originalCanvas.value.width = width
              originalCanvas.value.height = height
              // 显示图片到原始canvas
              const ctx = originalCanvas.value.getContext('2d')
              ctx.clearRect(0, 0, width, height)
              ctx.drawImage(img, 0, 0, width, height)
              
              // 保存原始图像数据
              if (originalMat) {
                originalCanvas.delete()
              }
              
             
            
          }, 0)
        }
        img.src = e.target.result
      }
      reader.readAsDataURL(file)
    }
  }
  input.click()
}
// 多图选择方法
const imageList = ref([]); // 存储图片数据的数组
const selectImages = async() => {
  // 清空旧数据
  imageList.value = []
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.multiple = true; // 关键属性：允许多选
  input.max = 9; // 限制最多选择9张图片

  input.onchange = async (e) => {
    imageList.value = Array.from(e.target.files); // 将FileList转为数组

    // 限制最多9张图片
    if (imageList.value.length > 9) {
      alert('最多只能选择9张图片');
      return;
    }
    creatCanvas(imageList.value);

  
  };
  input.click();
};

//动态添加canvas并设置第一个为大canvas显示
const canvasContent = ref(null);
const creatCanvas=async(imageList)=>{
  // 清空之前的 canvas
  while (canvasContent.value.firstChild) {
        canvasContent.value.removeChild(canvasContent.value.firstChild);
      }
  imageList.forEach((element,index) => {
    const canvas=document.createElement('canvas')
    canvas.dataset.index=index;
    
  });
}

// 发送图像给worker//imgObj{imgObj:[imgid,image],threshold}

const sendImage = async () => {
  // 获取 Mat 的原始数据及元信息
  const originalData  = originalMat.data; // Uint8Array
  const dataCopy = new Uint8Array(originalData.length);
  dataCopy.set(originalData); // 复制数据到新内存区域
  worker.postMessage({
    imgObj: {
      imgid: 1,
      data: dataCopy,
      width: originalMat.cols,
      height: originalMat.rows,
      channels: originalMat.channels(),
      type: originalMat.type() // 可选，明确数据类型
    },
    threshold: 16
  }, [dataCopy.buffer]); // 使用 Transferable 提升性能
};




// 组件卸载时清理内存和定时器
onUnmounted(() => {

})

onMounted(async()=>{
 
  
 
})
</script>

<style scoped>
.container {
  font-size: 0.1rem;

  padding: 0.02rem;
  background-color: #f5f5f5;
  color: #000;
}

.main-content {
  display: flex;
  gap: 0.02rem;
  height: 100%;
  width: 100%;
}

.image-container {
  position: relative;
  width: 7rem;
  height: 4.5rem;
  justify-content: center;
  align-items: center;
  background-color: #000;
  padding: 0.01rem;
}

.grid-container {
  width: 100%;
  height: 100%;

  padding: 0.01rem;
}

.grid-item {
  position: relative;
  background-color: #000;
  width: 100%;
  height: 100%;
  border: 1px solid #333;
}

.grid-item canvas {
  width: 100% !important;
  height: 100% !important;
  object-fit: fill;
}
.grid-items{
  padding-top: 0.1rem;
  display: flex;
  align-items: center;
  justify-content:space-between;
}



.control-panel {
  width: 3rem;
  background-color: white;
  padding: 0.02rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.panel-section{
  margin-top:0.05rem ;
  margin-bottom: 0.05rem;
  background-color: #e4e4e4;
  max-height: 2rem;
}
.table-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-section .child{
  margin-top:0.05rem ;
  margin-bottom: 0.05rem;
  
}
.panel-section .child .bt{
  margin-right:0.05rem ;
  
}
.tab-header {

  display: flex;
  margin-bottom: 0.02rem;
  border-bottom: 1px solid #c7c7c7;
}

.tab-btn {
  font-size: 0.1rem;
  width: 1rem;
  height: 0.2rem;
  padding: 0.02rem 0.2rem;
  border: none;
  background: none;
  cursor: pointer;
}

.tab-btn.active {
  border-bottom: 2px solid #4CAF50;
  color: #4CAF50;
}



.button-group {
  display: flex;
  gap: 0.05rem;
}

button {
  font-size: 0.08rem;
  width: 0.6rem;
  height: 0.2rem;
  padding: 0.02rem 0.02rem;
  background-color: #4CAF50;
  color: rgb(0, 0, 0);
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.threshold-control {
  display: flex;
  align-items: center;
  gap: 0.05rem;
}

.threshold-input-group {
  display: flex;
  align-items: center;
  gap: 0.05rem;
  flex: 1;
}

.adjust-btn {
  width: 0.2rem;
  height: 0.2rem;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4CAF50;
  color: rgb(0, 0, 0);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
}

.adjust-btn:hover {
  background-color: #45a049;
}

.adjust-btn:active {
  background-color: #3d8b40;
}

input[type="range"] {
  width: 1.4rem;
  margin: 0 4px;
}

input[type="number"] {
  width: 0.5rem;
  padding: 4px;
  border: 1px solid #000000;
  border-radius: 4px;
  text-align: center;
}

input[type="number"]:focus {
  outline: none;
  border-color: #4CAF50;
}

.results, .channel-results {
  display: flex;
  flex-direction: column;
  gap: 0.05rem;
}

.result-item {
  display: flex;
  align-items: center;
  gap: 0.05rem;
}

.result-item input {
  width: 1rem;
  padding: 4px;
}



.count-display {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: bold;
  color: #000;
  border: 1px solid #000000;
}
.table-section{
  height: 1.8rem;
}


</style>